"""
循环经济环境影响评估模块
"""
import json
import os

class EnvironmentalAnalyzer:
    def __init__(self):
        # 从JSON文件加载产品数据
        self.product_data = self._load_product_data()
    
    def _load_product_data(self):
        """加载产品数据"""
        data_path = os.path.join(os.path.dirname(__file__), 'data', 'products.json')
        try:
            with open(data_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
                return {p['type']: p for p in data['products']}
        except Exception as e:
            raise ValueError(f"无法加载产品数据: {str(e)}")
    
    def assess_impact(self, product_type, quantity):
        """
        评估回收产品的环境影响
        参数:
            product_type: 产品类型
            quantity: 数量
        返回:
            字典包含各项环境指标
        """
        if product_type not in self.product_data:
            supported = ", ".join(self.product_data.keys())
            raise ValueError(f"不支持的产品类型: {product_type}。支持的类型有: {supported}")
            
        product = self.product_data[product_type]
        
        # 计算总碳减排量(kg CO2)
        total_co2 = product['co2_per_unit'] * quantity
        
        # 计算可回收材料量(kg)
        material_saving = quantity * product['weight_kg'] * product['material_recovery']
        
        # 计算有害物质处理量(kg)
        hazardous = quantity * product['weight_kg'] * product['hazardous_material']
        
        # 增强版环境评分(0-100)
        recovery_score = product['material_recovery'] * 40  # 0-40分
        hazard_penalty = product['hazardous_material'] * 30  # 0-30分扣分
        lifespan_bonus = min(20, product.get('lifespan_years', 1) * 2)  # 每年寿命加2分，最多20分
        env_score = min(100, 50 + recovery_score - hazard_penalty + lifespan_bonus)
        
        return {
            '产品类型': product_type,
            '数量': quantity,
            '碳减排量(kg CO2)': round(total_co2, 2),
            '可回收材料量(单位)': round(material_saving, 2),
            '有害物质处理量(单位)': round(hazardous, 2),
            '环境效益评分(0-100)': round(env_score, 2)
        }